<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Traits\LogsActivity;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class AdminCategoryController extends Controller
{
    use LogsActivity;
    /**
     * 显示分类列表
     */
    public function index(): Response
    {
        $categories = Category::withCount('products')
            ->orderBy('sort_order')
            ->orderBy('name')
            ->get()
            ->map(function ($category) {
                return [
                    'id' => $category->id,
                    'name' => $category->name,
                    'slug' => $category->slug,
                    'description' => $category->description,
                    'is_active' => $category->is_active,
                    'sort_order' => $category->sort_order,
                    'products_count' => $category->products_count,
                    'created_at' => $category->created_at,
                    'updated_at' => $category->updated_at,
                ];
            });

        return Inertia::render('Admin/Categories/Index', [
            'categories' => $categories,
        ]);
    }

    /**
     * 显示创建分类表单
     */
    public function create(): Response
    {
        return Inertia::render('Admin/Categories/Create');
    }

    /**
     * 存储新分类
     */
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'slug' => 'required|string|max:255|unique:categories,slug',
            'description' => 'nullable|string',
            'is_active' => 'boolean',
            'sort_order' => 'integer|min:0',
        ]);

        $category = Category::create([
            'name' => $request->name,
            'slug' => $request->slug,
            'description' => $request->description,
            'is_active' => $request->boolean('is_active', true),
            'sort_order' => $request->sort_order ?? 0,
        ]);

        // 记录日志
        $this->logCreate(
            module: 'categories',
            itemName: $category->name,
            model: $category
        );

        return redirect()->route('categories.index')
            ->with('success', '分类创建成功！');
    }

    /**
     * 显示编辑分类表单
     */
    public function edit(Category $category): Response
    {
        // 获取该分类下的产品
        $products = $category->products()
            ->with(['images'])
            ->orderBy('created_at', 'desc')
            ->get()
            ->map(function ($product) {
                return [
                    'id' => $product->id,
                    'name' => $product->name,
                    'description' => $product->description,
                    'price' => $product->price,
                    'compare_price' => $product->compare_price,
                    'is_active' => $product->is_active,
                    'is_featured' => $product->is_featured,
                    'images' => $product->images->map(function ($image) {
                        return [
                            'id' => $image->id,
                            'url' => $image->image_path,
                            'alt' => $image->alt_text,
                        ];
                    }),
                ];
            });

        return Inertia::render('Admin/Categories/Edit', [
            'category' => [
                'id' => $category->id,
                'name' => $category->name,
                'slug' => $category->slug,
                'description' => $category->description,
                'is_active' => $category->is_active,
                'sort_order' => $category->sort_order,
            ],
            'products' => $products,
        ]);
    }

    /**
     * 更新分类
     */
    public function update(Request $request, Category $category)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'is_active' => 'boolean',
            'sort_order' => 'integer|min:0',
        ]);

        $category->update([
            'name' => $request->name,
            'description' => $request->description,
            'is_active' => $request->boolean('is_active'),
            'sort_order' => $request->sort_order,
        ]);

        // 记录日志
        $this->logUpdate(
            module: 'categories',
            itemName: $category->name,
            model: $category
        );

        return redirect()->route('categories.index')
            ->with('success', '分类更新成功！');
    }

    /**
     * 删除分类
     */
    public function destroy(Category $category)
    {
        // 检查是否有产品关联
        if ($category->products()->count() > 0) {
            return redirect()->route('categories.index')
                ->with('error', '无法删除有关联产品的分类！');
        }

        $categoryName = $category->name;
        $category->delete();

        // 记录日志
        $this->logDelete(
            module: 'categories',
            itemName: $categoryName,
            model: null
        );

        return redirect()->route('categories.index')
            ->with('success', '分类删除成功！');
    }

    /**
     * 切换分类状态
     */
    public function toggleStatus(Category $category)
    {
        $oldStatus = $category->is_active;
        $category->update([
            'is_active' => !$category->is_active,
        ]);
        $newStatus = $category->is_active;

        // 记录日志
        $this->logToggleStatus(
            module: 'categories',
            itemName: $category->name,
            status: $newStatus ? '启用' : '禁用',
            model: $category
        );

        return redirect()->route('categories.index')
            ->with('success', '分类状态更新成功！');
    }
}